package com.online.fund.spider;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.online.fund.spider.dao.FundDao;
import com.online.fund.spider.entity.FundDetail;
import com.online.fund.util.DateUtils;
import com.online.fund.util.HttpClientUtil;

@Service
public class FundPageProcesser {

	private final static String FUND_PAGE_URL = "http://fund.eastmoney.com/";
	private final static String FUND_PAGE_URL_SUFFIX = ".html";
	
	private final static Logger logger = LoggerFactory.getLogger(FundPageProcesser.class);
	
	@Resource
	private FundDao fundDao;
	
	public void parsePage(String fundCode) {
		parsePage(fundCode, true);
	}
	
	public void parsePage(String fundCode, boolean saveFlag) {
		try {
			String pageHtml = HttpClientUtil.httpGetRequest(FUND_PAGE_URL + fundCode + FUND_PAGE_URL_SUFFIX);
			Document doc = Jsoup.parse(pageHtml);
			FundDetail fundDetail = new FundDetail();
			fundDetail.setFundCode(fundCode);
			fundDetail.setFundName(doc.select("div.fundDetail-tit > div").first().ownText());
			fundDetail.setCrawlDate(DateUtils.getCurrentDate());
			
			Element fundDetailElement = doc.select("div.infoOfFund > table").first();
			Elements detailElements = fundDetailElement.getElementsByTag("TD");
			// 基金类型 | 风险级别
			String fundTypeAndRiskLevel = detailElements.get(0).text();
			if (detailElements.get(0).getElementsByTag("A").size() == 0) {
				fundTypeAndRiskLevel = fundTypeAndRiskLevel.replace("基金类型：", "");
				// 保本型  |  中低风险
				if (fundTypeAndRiskLevel.contains("  |")) {
					fundDetail.setFundType(fundTypeAndRiskLevel.substring(0, fundTypeAndRiskLevel.indexOf("  |")));
				} else if (!fundTypeAndRiskLevel.contains("|")) {
					fundDetail.setFundType(fundTypeAndRiskLevel);
				}
			} else {
				fundDetail.setFundType(detailElements.get(0).getElementsByTag("A").text());
			}
			
			// 风险级别
			if (fundTypeAndRiskLevel.contains("|")) {
				fundDetail.setRiskLevel(fundTypeAndRiskLevel.substring(fundTypeAndRiskLevel.indexOf("|  ") + "|  ".length()));
			}

			// 基金规模+日期
			String content = detailElements.get(1).text();
			Pattern pattern = Pattern.compile("-*\\d+(\\.\\d+)?");
			Matcher matcher = pattern.matcher(content);
			if (matcher.find()) {
				fundDetail.setFundSize(Double.parseDouble(matcher.group(0)));
			}
			
			pattern = Pattern.compile("\\d{4}\\-\\d{1,2}-\\d{1,2}");
			matcher = pattern.matcher(content);
			if (matcher.find()) {
				fundDetail.setFundSizeDate(matcher.group(0));
			}
			
			// 基金成立日
			matcher = pattern.matcher(detailElements.get(3).text());
			if (matcher.find()) {
				fundDetail.setEstablishDate(matcher.group(0));
			}
			
			// 基金评级
			if (!detailElements.get(5).text().contains("暂无评级")) {
				String fundRatingCss = detailElements.get(5).select("div").first().className();
				pattern = Pattern.compile("\\d");
				matcher = pattern.matcher(fundRatingCss);
				if (matcher.find()) {
					fundDetail.setFundRating(matcher.group(0));
				} 
			}
			
			if ("固定收益".equals(fundDetail.getFundType())) {
				// 单位净值
				String netAssetValue = doc.select("dl.dataItem03 > dd.dataNums > span").first().text();
				if (!"".equals(netAssetValue)) {
					fundDetail.setNetAssetValue(Double.parseDouble(netAssetValue));
				}
			} else {
				// 单位净值
				String netAssetValue = doc.select("dl.dataItem02 > dd.dataNums > span").first().text();
				if (!"".equals(netAssetValue) && !netAssetValue.contains("月")) {
					fundDetail.setNetAssetValue(Double.parseDouble(netAssetValue));
				}
				
				// 累计净值
				String accumulativeTotalNetValue = doc.select("dl.dataItem03 > dd.dataNums > span").first().text();
				if (!"".equals(accumulativeTotalNetValue)) {
					fundDetail.setAccumulativeTotalNetValue(Double.parseDouble(accumulativeTotalNetValue));
				}
				
				
				// 1月
				Element dataOfFundElement = doc.select("div.dataOfFund").first();
				String oneMonthChangeRate = dataOfFundElement.select("dl.dataItem01 > dd").get(1).select("span.ui-font-middle").text().replace("%", "");
				if (!"--".equals(oneMonthChangeRate)) {
					fundDetail.setOneMonthChangeRate(Double.parseDouble(oneMonthChangeRate));
				}
				
				String threeMonthChangeRate = dataOfFundElement.select("dl.dataItem02 > dd").get(1).select("span.ui-font-middle").text().replace("%", "");
				if (!"--".equals(threeMonthChangeRate)) {
					fundDetail.setThreeMonthChangeRate(Double.parseDouble(threeMonthChangeRate));
				}
				
				String sixMonthChangeRate = dataOfFundElement.select("dl.dataItem03 > dd").get(1).select("span.ui-font-middle").text().replace("%", "");
				if (!"--".equals(sixMonthChangeRate)) {
					fundDetail.setSixMonthChangeRate(Double.parseDouble(sixMonthChangeRate));
				}
				
				String oneYearChangeRate = dataOfFundElement.select("dl.dataItem01 > dd").get(2).select("span.ui-font-middle").text().replace("%", "");
				if (!"--".equals(oneYearChangeRate)) {
					fundDetail.setOneYearChangeRate(Double.parseDouble(oneYearChangeRate));
				}
				
				String threeYearChangeRate = dataOfFundElement.select("dl.dataItem02 > dd").get(2).select("span.ui-font-middle").text().replace("%", "");
				if (!"--".equals(threeYearChangeRate)) {
					fundDetail.setThreeYearChangeRate(Double.parseDouble(threeYearChangeRate));
				}
				
				String allChangeRate = dataOfFundElement.select("dl.dataItem03 > dd").get(2).select("span.ui-font-middle").text().replace("%", "");
				if (!"--".equals(allChangeRate)) {
					fundDetail.setAllChangeRate(Double.parseDouble(allChangeRate));
				}
			}
			
			// 开放申购 限大额 (单日投资上限500万元)
			String purchaseStatus = doc.select("div.buyWayStatic span.staticCell").get(0).text();
			if (purchaseStatus != null && purchaseStatus.contains("限大额")) {
				fundDetail.setPurchaseStatus("开放申购");
			} else {
				fundDetail.setPurchaseStatus(purchaseStatus);
			}
			// 赎回状态
			fundDetail.setRedemptionStatus(doc.select("div.buyWayStatic span.staticCell").get(1).text());
			
			if (saveFlag) {
				fundDao.deleteFund(fundCode, fundDetail.getCrawlDate());
				fundDao.addFund(fundDetail);
			} else {
				System.out.println(fundDetail);
			}
			System.out.println(fundCode);
			
			
//			System.out.println(dataOfFundElement.select("dl.dataItem01 > dd").get(1).select("span.ui-font-middle").text().replace("%", ""));
//			System.out.println(doc.select("div.buyWayStatic span.staticCell").get(0).text());
//			System.out.println(doc.select("div.buyWayStatic span.staticCell").get(1).text());
//			System.out.println(fundDetail);
		} catch (Exception e) {
			logger.error(fundCode, e);
		}
		
	}
	
	public static void main(String[] args) throws IOException {
		FundPageProcesser pageProcesser = new FundPageProcesser();
		pageProcesser.parsePage("160610", false);
	}
}
 